const express = require('express');
const fs = require('fs');
const time = require('time-stamp');
const app = express();
const path = require('path');
const formidable = require('formidable')

app.listen(3000);
app.use('/static', express.static(path.join(__dirname, 'static')));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use((req, res, next) => {
    req.time = time('YYYY年MM月DD日  HH:mm:ss');
    next();
});
// 获取persons.json数据
let dir = path.join(__dirname, '/persons.json');
let data = fs.readFileSync(dir, 'utf-8');
data = JSON.parse(data);
// 渲染页面
app.get('/register', (req, res) => {
    res.sendFile(path.join(__dirname, 'register.html'))
})


// 注册逻辑
app.post('/upload', (req, res) => {
    let form = formidable({
        uploadDir: path.join(__dirname, 'upload'),
        keepExtensions: true,
    })
    form.parse(req,(err,{ tel, pass, pass2 },files)=>{
        console.log(tel, pass, pass2);
        let oldpath=files.photo.filepath;
        let newpath=path.join(__dirname,'upload',files.photo.originalFilename);
        fs.renameSync(oldpath,newpath);
    // 传参不能为空
    if (!tel || !pass || !pass2) {
        res.send({ code: 400, msg: '请输入有效内容' })
    }
    // 判断两次密码是否一致
    if (pass != pass2) {
        res.send({ code: 400, msg: '两次密码输入不一致' })
    }
    // 判断是否存在
    let s = data.find(item => item.username == tel);
    if (s) {
        res.send({ code: 400, msg: '用户名已存在' })
    }
    // let photo=fs.readFileSync('/upload','utf-8')
    // 用户名不存在可注册
    data.push({ username: tel, password: pass, time: req.time,url:newpath });
    fs.writeFileSync(dir, JSON.stringify(data));
    res.send({ code: 200, msg: '注册成功' })
    })
  

})
